const Core = require('@alicloud/pop-core');
require('dotenv').config();

// 修改为ECS服务配置
const client = new Core({
    accessKeyId: process.env.ALIYUN_IHEALTHIFY_ACCESS_KEY_ID,
    accessKeySecret: process.env.ALIYUN_IHEALTHIFY_ACCESS_KEY_SECRET,
    endpoint: 'https://ecs.aliyuncs.com',  // 改为ECS的API端点[8](@ref)
    apiVersion: '2014-05-26'  // ECS API版本号[6,8](@ref)
});

async function listECSInstances() {
    const params = {
        RegionId: 'cn-beijing',  // 根据实际情况修改地域
        PageNumber: 1,            // 分页参数
        PageSize: 100             // 每页最大100条记录[7](@ref)
    };

    try {
        // 调用DescribeInstances接口[6,8](@ref)
        const result = await client.request('DescribeInstances', params, { 
            method: 'POST',
            formatParams: false  // 禁用参数自动格式化
        });

        // 格式化输出实例信息
        console.log('ECS实例列表：');
        result.Instances.Instance.forEach(instance => {
            console.log(`实例ID：${instance.InstanceId}`);
            console.log(`实例名称：${instance.InstanceName}`);
            console.log(`公网IP：${instance.PublicIpAddress.IpAddress[0] || '无'}`);
            console.log(`状态：${instance.Status}`);
            console.log('------------------------');
        });

        return result;
    } catch (error) {
        console.error('API调用失败:', {
            code: error.code,
            message: error.data?.Message || error.message,
            requestId: error.requestId  // 调试用请求ID[6](@ref)
        });
        throw error;
    }
}
async function servers() {
    await listECSInstances();
}
//servers();

async function getSecurityGroupId(instanceId) {
    const params = {
        RegionId: 'cn-beijing',          // 根据实例地域修改[3](@ref)
        InstanceIds: JSON.stringify([instanceId]) // 支持批量查询，此处单实例[7](@ref)
    };

    try {
        const response = await client.request('DescribeInstances', params, { 
            method: 'POST',
            formatParams: false
        });

        // 解析安全组ID
        const instances = response.Instances.Instance;
        if (instances.length === 0) {
            throw new Error('实例不存在');
        }

        //

        const securityGroupIds = instances[0].SecurityGroupIds.SecurityGroupId;
        console.log('实例关联安全组ID列表:', instances[0].SecurityGroupIds);
        return securityGroupIds;
    } catch (error) {
        console.error('查询失败:', {
            code: error.code,
            message: error.data?.Message || error.message,
            requestId: error.requestId      // 调试关键字段[7](@ref)
        });
        throw error;
    }
}

async function security() {
    const instanceId = 'i-2ze3snus7dpunqpw6mjo';
    const sgIds = await getSecurityGroupId(instanceId);
    console.log('主安全组ID:', sgIds[0]); // 通常取第一个安全组操作
}
//security();

//主安全组ID: sg-2zed4hz02h807gdf1c2h
async function listSecurityGroupRules() {
    const params = {
        RegionId: 'cn-beijing',              // 根据实际地域修改[7](@ref)
        SecurityGroupId: 'sg-2zed4hz02h807gdf1c2h',
        Direction: 'all',                     // 同时查询入/出方向规则[7](@ref)
        MaxResults: 100                       // 单次最多获取100条规则[7](@ref)
    };

    try {
        const response = await client.request('DescribeSecurityGroupAttribute', params, {
            method: 'POST',
            formatParams: false
        });

        // 格式化输出规则
        console.log('安全组规则详情：');
        response.Permissions.Permission.forEach(rule => {
            console.log(`规则方向：${rule.Direction}`);
            console.log(`协议类型：${rule.IpProtocol}`);
            console.log(`端口范围：${rule.PortRange}`);
            console.log(`授权对象：${rule.SourceCidrIp || rule.DestCidrIp}`);
            console.log(`优先级：${rule.Priority}`);
            console.log(`策略：${rule.Policy}`);
            console.log('------------------------');
        });

        return response;
    } catch (error) {
        console.error('查询失败:', {
            code: error.code,
            message: error.data?.Message || error.message,
            requestId: error.requestId        // 调试关键字段[7](@ref)
        });
        throw error;
    }
}
async function rules() {
    await listSecurityGroupRules();
}
rules();

async function openPorts() {
    const baseParams = {
        RegionId: 'cn-beijing',
        SecurityGroupId: 'sg-2zed4hz02h807gdf1c2h',
        IpProtocol: 'TCP',
        Policy: 'accept',
        Priority: 1,
        SourceCidrIp: '0.0.0.0/0'
    };

    try {
        // 创建7000端口规则
        await client.request('AuthorizeSecurityGroup', {
            ...baseParams,
            PortRange: '7000/7000',
            SourceCidrIp: '0.0.0.0/0',
            Description: '开放FRP服务端口'
        }, { method: 'POST' });

        // 创建6000端口规则
        await client.request('AuthorizeSecurityGroup', {
            ...baseParams,
            PortRange: '6000/6000',
            Description: '开放备用端口'
        }, { method: 'POST' });

        console.log('端口7000和6000已成功创建');
    } catch (error) {
        console.error('配置失败:', {
            code: error.code,
            message: error.data?.Message || error.message,
            requestId: error.requestId
        });
    }
}
//async function ports() { await openPorts(); }

